package com.example.wasaimovie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.wasaimovie.Annotation.DisableBaseResponse;
import com.example.wasaimovie.Model.entity.*;
import com.example.wasaimovie.Model.support.ResponseResult;
import com.example.wasaimovie.Service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api")
@Slf4j
@CrossOrigin
@Transactional // 事务标签
public class FilmController {

    @Autowired
    PosterService posterService;

    @Autowired
    FilmService filmService;

    @Autowired
    UserService userService;

    @Autowired
    FilmEvaluateService filmEvaluateService;

    @Autowired
    ArrangementService arrangementService;

    @Autowired
    OrderService orderService;

    @Value("${movie.image.url.path}")
    String url;

    /**
     * 查询首页轮播图
     * @return 返回轮播图信息
     */
    @GetMapping("/poster")
    @DisableBaseResponse
    public ResponseResult<List<Poster>> poster(){
        log.info("FilmController --> poster");
        List<Poster> list = posterService.list();
        for (Poster p : list){
            p.setUrl("http://localhost:8888/api/upload/" + p.getUrl());
        }
        ResponseResult<List<Poster>> result = new ResponseResult<>(200, true, null, list);
        return result;
    }

    @GetMapping("/film/{type}/{region}")
    public List<Film> getfilm(@PathVariable String type,
                              @PathVariable String region){
        log.info("FilmController --> getfilm");
        QueryWrapper<Film> qw = new QueryWrapper<>();
        if (!type.equals("全部")){
            qw.eq("type", type);
        }
        if (!region.equals("全部")){
            qw.eq("region", region);
        }
        List<Film> films = filmService.list(qw);

        for (Film fil : films){
            fil.setCover(url + fil.getCover());
        }
        return films;
    }

    /**
     * 查询热门电影前 limit 项
     * @param limit 查询的数量
     * @return 返回热门电影信息
     */
    @CrossOrigin
    @GetMapping("/film/hot/{limit}")
    public List<Film> getTopLimit(@PathVariable int limit){
        List<Film> films = filmService.selectByHot(10);
        return films;
    }

    /**
     * 模糊查询，按电影名字查询
     * @param name 模糊查询的信息
     * @return 返回电影信息
     */
    @GetMapping("/film/name/{name}")
    public List<Film> querySearchFilm(@PathVariable String name){
        List<Film> list = null;
        QueryWrapper<Film> qw = new QueryWrapper<>();
        qw.like("name", name);
        list = filmService.list(qw);
        for (Film film : list) {
            film.setCover(url + film.getCover());
        }
        return list;
    }

    /**
     * 获取电影信息
     * @param id 电影id
     * @return 电影详细信息
     */
    @GetMapping("/film/{id}")
    public Film getFilmDetail(@PathVariable String id){
        QueryWrapper<Film> qw = new QueryWrapper<>();
        qw.eq("id", id);
        Film film = filmService.list(qw).get(0);
        film.setCover(url + film.getCover());
        return film;
    }

    /**
     * 查询电影评论
     * @param fid 电影id
     * @return 所有评论以及对应id
     */
    @GetMapping("/fe/{fid}")
    public List<Map<String, Object>> getFilmEvaluate(@PathVariable String fid){
        List<Map<String, Object>> result = new ArrayList<>();
        QueryWrapper<FilmEvaluate> qw = new QueryWrapper<>();
        qw.eq("fid", fid);
        List<FilmEvaluate> list = filmEvaluateService.list(qw);

        // 根据list中的Uid查询用户
        list.forEach((filmEvaluate -> {
            System.out.println(filmEvaluate);
            User user = userService.getById(filmEvaluate.getUid());
            if (user != null){
                if (user.getAvatar().indexOf('/') < 0){
                    user.setAvatar(url + user.getAvatar());
                }
            } else {
                user = new User();
                user.setNickname("用户已注销");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("id", filmEvaluate.getId());
            map.put("filmEvaluate", filmEvaluate);
            map.put("user", user);
            result.add(map);
        }));
        return result;
    }

    /**
     * 评论电影
     * @param filmEvaluate 评论信息
     * @return 评论结果
     */
    @DisableBaseResponse
    @PostMapping("/fe")
    public ResponseResult<Object> FilmScore(@RequestBody FilmEvaluate filmEvaluate){
        log.info("FilmController -> FilmScore");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();

        filmEvaluate.setId(UUID.randomUUID().toString());
        filmEvaluate.setCreateTime(format.format(date));
        filmEvaluateService.save(filmEvaluate);
        return new ResponseResult<>(200);
    }

    /**
     * 查询电影排片信息
     * @param fid 电影id
     * @return 电影场次
     */
    @GetMapping("/arrangement/film/{fid}")
    public Map<String, Object> getarrangementByFid(@PathVariable String fid){
        Map<String, Object> result = new HashMap<>();
        // 排片信息
        QueryWrapper<Arrangement> qw = new QueryWrapper<>();
        qw.eq("fid", fid);
        List<Arrangement> list = arrangementService.list(qw);

        // 电影信息
        QueryWrapper<Film> qw1 = new QueryWrapper<>();
        qw1.eq("id", fid);
        Film film = filmService.list(qw1).get(0);

        // 加入map
        result.put("arrangements", list);
        result.put("film", film);
        return result;
    }

    /**
     * 查询电影场次信息
     * @param id 场次id
     * @return 场次信息
     */
    @GetMapping("/arrangement/{id}")
    public Map<String, Object> getArrangementById(@PathVariable String id){
        Map<String, Object> result = new HashMap<>();
        // 查询场次信息
        QueryWrapper<Arrangement> qw = new QueryWrapper<>();
        qw.eq("id", id);
        Arrangement arrangement = null;
        List<Arrangement> list = arrangementService.list(qw);
        if (!list.isEmpty()){
            // 如果list中有参数
            arrangement = list.get(0);
            // 查询电影信息
            QueryWrapper<Film> filmQueryWrapper = new QueryWrapper<>();
            filmQueryWrapper.eq("id", arrangement.getFid());
            Film film = filmService.list(filmQueryWrapper).get(0);
            film.setCover(url + film.getCover());

            //整合结果
            result.put("arrangement", arrangement);
            result.put("film", film);
        }
        return result;
    }

    /**
     * 查询某一场次座位信息
     * @param id 场次id
     * @return 已被售出的位置
     */
    @GetMapping("/arrangement/getseats/{id}")
    public List<String> getSeats(@PathVariable String id){
        log.info("FilmController -> getSeats");
        List<String> seats = orderService.getSeats(id);
        return seats;
    }

    /**
     * 根据id修改电影信息
     * @param film 电影信息
     * @return 是否修改成功
     */
    @PutMapping("/film")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> reviseFilm(@RequestBody Film film){
        System.out.println(film);
        int index = film.getCover().lastIndexOf("/");
        film.setCover(film.getCover().substring(index + 1));
        boolean b = filmService.updateById(film);
        if (b){
            return new ResponseResult<>(200, null);
        } else {
            return new ResponseResult<>(400,"电影信息错误");
        }
    }

    /**
     * 删除电影
     * @param id 电影id
     * @return 是否删除成功
     */
    @DeleteMapping("/film/{id}")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> deleteFilm(@PathVariable String id){
        QueryWrapper<Film> qw = new QueryWrapper<>();
        qw.eq("id", id);
        Film film = filmService.list(qw).get(0);
        String fileName = film.getName();
        boolean remove = filmService.remove(qw);
        if (remove){
            // 删除图片
            File image = new File("D:\\javaweb\\IdeaProjects\\WaSaiMovie\\src\\main\\resources\\static\\image\\" + fileName);
            if (image.exists()){
                image.delete();
            }
            return new ResponseResult<>(200, null);
        }

        return new ResponseResult<>(400, "删除失败");
    }

    /**
     * 电影排片
     * @param arrangement 排片信息
     * @return 是否成功
     */
    @PostMapping("/arrangement")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> arrangementFilm(@RequestBody Arrangement arrangement){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        arrangement.setCreateTime(format.format(new Date()));
        arrangement.setId(UUID.randomUUID().toString());
        boolean save = arrangementService.save(arrangement);
        if (save){
            return new ResponseResult<>(200, null);
        }

        return new ResponseResult<>(400,"删除失败");
    }

    /**
     * 获取所有排片信息
     * @return 排片信息
     */
    @GetMapping("/arrangement")
    @CrossOrigin
    public List<Arrangement> getArrangement(){
        return arrangementService.list();
    }

    /**
     * 电影排片的模糊查询
     * @param name 电影名
     * @return 排片信息
     */
    @GetMapping("/arrangement/like/{name}")
    @CrossOrigin
    public List<Arrangement> likeArrangement(@PathVariable String name){
        QueryWrapper<Arrangement> qw = new QueryWrapper<>();
        qw.like("name", name);
        return arrangementService.list(qw);
    }

    /**
     * 根据ID修改排片信息
     * @param arrangement 新的排片信息
     * @return 是否修改成功
     */
    @PutMapping("/arrangement")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> editArrangement(@RequestBody Arrangement arrangement){
        boolean b = arrangementService.updateById(arrangement);
        if (b){
            return new ResponseResult<>(200,null);
        }
        return new ResponseResult<>(400, "修改失败");
    }

    /**
     * 根据ID删除排片
     * @param id 排片id
     * @return 是否删除成功
     */
    @DeleteMapping("/arrangement/{id}")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> deleteArrangement(@PathVariable String id){
        QueryWrapper<Arrangement> qw = new QueryWrapper<>();
        qw.eq("id", id);
        boolean remove = arrangementService.remove(qw);
        if (remove){
            return new ResponseResult<>(200, null);
        }

        return new ResponseResult<>(400, "删除失败");
    }

    /**
     * 添加电影
     * @param film 电影信息
     * @return 是否添加成功
     */
    @PostMapping("/film")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> addFilm(@RequestBody Film film){
        film.setId(UUID.randomUUID().toString());
        String imageName = film.getCover();
        int index = imageName.lastIndexOf('/');
        film.setCover(imageName.substring(index + 1));
        if (filmService.save(film)){
            return new ResponseResult<>(200, null);
        }
        return new ResponseResult<>(400, "添加失败");
    }

    /**
     * 添加轮播图
     * @param poster 轮播图信息
     * @return 是否上传成功
     */
    @PostMapping("/poster")
    @DisableBaseResponse
    @CrossOrigin
    public ResponseResult<Object> addPoster(@RequestBody Poster poster){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        poster.setId(UUID.randomUUID().toString());
        poster.setCreateTime(format.format(new Date()));
        poster.setUpdateTime(format.format(new Date()));
        poster.setUrl(poster.getUrl().substring(poster.getUrl().lastIndexOf('/') + 1));
        // 查询t_film表中是否有这个电影
        QueryWrapper<Film> qw = new QueryWrapper<>();
        qw.eq("name", poster.getTitle());
        List<Film> list = filmService.list(qw);
        if (!list.isEmpty()){
            poster.setFid(list.get(0).getName());
        } else {
//            return new ResponseResult<>(400, "不存在该电影");
        }

        boolean save = posterService.save(poster);
        if (save){
            return new ResponseResult<>(200, null);
        }
        return new ResponseResult<>(400, "上传错误");
    }

    /**
     * 根据id更新轮播图
     * @param poster 更新信息
     * @return 是否更新成功
     */
    @PutMapping("/poster")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> updatePoster(@RequestBody Poster poster){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        poster.setUpdateTime(format.format(new Date()));
        poster.setUrl(poster.getUrl().substring(poster.getUrl().lastIndexOf('/') + 1));
        boolean b = posterService.updateById(poster);
        if (b){
            return new ResponseResult<>(200, null);
        }
        return new ResponseResult<>(400, "更新失败");
    }

    /**
     * 根据id删除轮播图
     * @param id 轮播图id
     * @return 是否删除成功
     */
    @DeleteMapping("/poster/{id}")
    @CrossOrigin
    @DisableBaseResponse
    public ResponseResult<Object> deletePoster(@PathVariable String id){
        boolean b = posterService.removeById(id);
        if (b){
            return new ResponseResult<>(200, null);
        }
        return new ResponseResult<>(400, "删除失败");
    }
}
